﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Eneta.Portal.Controls;
using Eneta.Portal.Common;

namespace Eneta.Portal.Literature.Controls
{
    public class LiteratureListingControl : UserControl
    {
        public string ContentTypeName { get;set; }
        public string WebUrl { get; set; }
        public bool ShowPendingItems { get; set; }

        protected Repeater BooksList;
        protected HtmlAnchor thumbnailLink;
        protected HtmlImage bookThumbnail;
        protected HtmlAnchor bookHeadingLink;
        protected HtmlGenericControl bookDescription;
        protected HtmlAnchor moreInfoLink;
        protected HtmlAnchor bookPosterProfileLink;
        protected HtmlGenericControl bookPosterName;
        protected HtmlGenericControl postDate;
        protected HtmlGenericControl commentsCount;
        protected HtmlImage bookPosterImage;

        public bool IsAdmin
        {
            get
            {
                var currentUser  = SPContext.Current.Web.CurrentUser;
                if (currentUser == null)
                    return false;
                return currentUser.IsSiteAdmin;
            }
        }
        
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            BooksList.ItemDataBound += new RepeaterItemEventHandler(BooksList_ItemDataBound);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                var repository = new LiteratureRepository(SPContext.Current.Web);
                if (!ShowPendingItems)
                {
                    Logger.LogInfo("Kuvame ainult kinnitatud raamatuid", "LiteratureListinControl_OnLoad");
                    BooksList.DataSource = repository.GetLiteratureItems(WebUrl, ContentTypeName);
                }
                else
                {
                    if (IsAdmin)
                    {
                        Logger.LogInfo("Kuvame kinnitatud ja sisseloginud kasutaja lisatud raamatuid", "LiteratureListinControl_OnLoad");
                        var items = repository.GetPendingAndApprovedItems(WebUrl, ContentTypeName, SPContext.Current.Web.CurrentUser);
                        BooksList.DataSource = items;
                    }
                    else
                    {
                        BooksList.DataSource = repository.GetUserAddedItems(WebUrl, ContentTypeName, SPContext.Current.Web.CurrentUser);
                    }
                }
                BooksList.DataBind();
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        //TODO: kommentaaride kuvamine pealkirjas
        void BooksList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;
            
            var book = e.Item.DataItem as LiteratureDto;
            if (book == null)
                return;
            var index = e.Item.ItemIndex;
            if (index == 0)
            {
                var blogItem = e.Item.FindControl("BlogItem") as HtmlGenericControl;
                if (blogItem != null)
                {
                    blogItem.Attributes.Remove("class");
                    blogItem.Attributes.Add("class", "blog blog-first");
                }   
            }
            var thumbnailLink = e.Item.FindControl("thumbnailLink") as HtmlAnchor;
            var bookThumbnail = e.Item.FindControl("bookThumbnail") as HtmlImage;
            var bookHeadingLink = e.Item.FindControl("bookHeadingLink") as HtmlAnchor;
            var bookDescription = e.Item.FindControl("bookDescription") as HtmlGenericControl;
            var moreInfoLink = bookDescription.FindControl("moreInfoLink") as HtmlAnchor;
            var bookPosterName = e.Item.FindControl("bookPosterName") as HtmlGenericControl;
            var bookPosterProfileLink = e.Item.FindControl("bookPosterProfileLink") as HtmlAnchor;
            var bookPosterImage = e.Item.FindControl("bookPosterImage") as HtmlImage;
            var postDate = e.Item.FindControl("postDate") as HtmlGenericControl;
            var commentsCount = e.Item.FindControl("commentsCount") as HtmlGenericControl;
            var bookTags = e.Item.FindControl("bookTags") as TagsViewControl;
            var blogFotoContainer = e.Item.FindControl("blogFotoContainer") as HtmlGenericControl;
            bookTags.Keywords = book.Keywords;

            var bookUrl = book.AdditionalInfoURL;
            /*switch(ContentTypeName)
            {
                case "Ajakiri":
                    bookUrl = "/oppimine/ajakirjad/LiteratureView.aspx?ID=" + book.ID;
                    break;
                case "Raamat":
                    bookUrl = "/oppimine/raamatud/LiteratureView.aspx?ID=" + book.ID;
                    break;
                default:
                    bookUrl = "/oppimine/raamatud/";
                    break;
            }
            */

            var web = SPContext.Current.Web;
            thumbnailLink.HRef = book.ItemUrl;
            Logger.LogInfo("Enne listi vaate pilti", "LiteratureListingControl");
            if (!string.IsNullOrEmpty(book.LiteratureSmallImageUrl))
            {
                SPWeb site = SPContext.Current.Site.RootWeb;
                SPFile picture = site.GetFile(book.LiteratureSmallImageUrl);
                Logger.LogInfo("Küsi fail: " + book.LiteratureSmallImageUrl, "Literature koondvaade");
                if (picture == null)
                {
                    bookThumbnail.Visible = false;
                }
                else if (picture != null && !picture.Exists)
                    bookThumbnail.Visible = false;

            }

            bookThumbnail.Alt = book.Title;
            bookHeadingLink.HRef = book.ItemUrl;
            bookHeadingLink.InnerHtml = book.Title;
            thumbnailLink.Title = book.Title;
            Logger.LogInfo("Seadistame pilti", "LiteratureListingControl_OnLoad:147");
            if (bookThumbnail == null)
                Logger.LogInfo("BookThumbnail on null", "LiteratureListingControl_OnLoad:149");
            if (bookThumbnail.Visible)
            {
                
                bookThumbnail.Src = book.LiteratureSmallImageUrl;
            }
            else
            {
                //bookThumbnail.Src = "/Style Library/eneta/images/generic_book_small.jpg";
                bookThumbnail.Visible = false;
                if (blogFotoContainer != null)
                    blogFotoContainer.Visible = false;
                else
                    Logger.LogInfo("blogFotoContainer on null", "LiteratureListingControl_OnLoad:162");
            }
            Logger.LogInfo("Küsime kommentaarid", "LiteratureListingControl_OnLoad:158");
            var parent = web.ParentWeb;
            if (parent != null)
            {
                var repository = new LiteratureRepository(web);
                var listInfo = web.ServerRelativeUrl + ";" + PublishingWeb.GetPagesListName(parent);
                var comments = repository.GetLiteratureComments(parent.ServerRelativeUrl, "LiteratureComments", listInfo, book.ID);
                if (comments != null)
                {
                    if (comments.Count != 0)
                    {
                        string count = " <span>({0})</span>";
                        bookHeadingLink.InnerHtml += string.Format(count, comments.Count); 
                    }
                }
            }
            var description = RegExHelper.RemoveHtmlTags(book.Summary);
            if (description.Length <= 255)
                bookDescription.InnerHtml = description;
            else
                bookDescription.InnerHtml = description.Substring(0, 255);
            bookDescription.InnerHtml += "&nbsp;<a class='more-info' href='"+book.ItemUrl+"' id='moreInfoLink' runat='server'>" + Resources.Literature.ReadMore +"</a>";

            bookPosterName.InnerText = book.Author;

            if (SPContext.Current.Web.CurrentUser != null)
            {
                var currentUserDisplayName = SPContext.Current.Web.CurrentUser.Name;

                if (currentUserDisplayName.Equals(book.Author))
                {
                    bookPosterName.InnerText = Resources.Literature.YouLabel;
                    bookPosterProfileLink.Title = Resources.Literature.YourProfileLabel;
                }
                else
                {
                    bookPosterProfileLink.HRef = UrlHelper.GetProfileUrl(book.PosterProfileId);
                    bookPosterProfileLink.Title = book.Author;
                }
            }
            else
            {
                bookPosterProfileLink.HRef = UrlHelper.GetProfileUrl(book.PosterProfileId);
                bookPosterProfileLink.Title = book.Author;
            }
            var profileRepository = new UserProfileRepository(web);
            var profile = profileRepository.GetUserProfileById(book.PosterProfileId);
            if (profile != null)
            {
                bookPosterImage.Src = profile.UserImage32x32Url;
            }
            else
            {
                bookPosterImage.Visible = false;
            }
            postDate.InnerText = book.PostedDate.ToString("dd.MM.yyyy");
            
        }
    }
}
